<script lang="ts" setup>
import { ref } from 'vue';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useI18n } from 'vue-i18n';
import { useAppStore } from '@/settings/stores';

const loading = ref(false);
const formData = ref({
  commTitle: '',
  commDesc: '',
  commKeywords: '',
  robotsContent: '',
});
const formRef = ref<FormInstance>();
const { success } = useNotification();
const { t } = useI18n();
const appStore = useAppStore();

const save = async () => {
  const { isSuccess } = await $fetch('/admin/community/editSEO', {
    method: 'post',
    data: {
      ...formData.value,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
    appStore.fetchConfig();
  }
};

const submit = async () => {
  const res = await formRef.value?.validate();

  if (res) {
    return;
  }

  save()
};

const getDetail = async () => {
  const { isSuccess, data } = await $fetch('/admin/community/getSEOInfo', {
    data: {
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    formData.value = {
      commTitle: data?.commTitle,
      commDesc: data?.commDesc,
      commKeywords: data?.commKeywords,
      robotsContent: data?.robotsContent,
    };
  }
}

getDetail();
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData" @submit="submit">
        <AFormItem :label="$t('settings.view.seo.title')" field="commTitle" :rules="[{ maxLength: 500 }]">
          <AInput v-model="formData.commTitle" :max-length="500" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.seo.description')" field="commDesc" :rules="[ { maxLength: 500 }]">
          <ATextarea v-model="formData.commDesc" :max-length="500" show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.seo.keywords')" field="commKeywords" :rules="[ { maxLength: 500 }]" :help="$t('settings.view.seo.keywordsHelp')">
          <ATextarea v-model="formData.commKeywords" :max-length="500" show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.seo.robots')" field="robotsContent">
          <ATextarea v-model="formData.robotsContent" class="h-500" />
        </AFormItem>

        <ADivider />

        <AFormItem>
          <ASpace><AButton html-type="submit" type="primary" :loading="loading">{{ $t('settings.action.submit') }}</AButton>
          </ASpace>
        </AFormItem>
      </AForm>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
</style>
